package com.gmall.rabbitmq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*
在开启重试模式后，重试次数耗尽，如果消息依然失败，
则需要由MessageRecoverer接口来处理，它包含三种不同的实现：

    RejectAndDontRequeueRecoverer：重试耗尽后，直接reject，丢弃消息。默认就是这种方式
    ImmediateRequeueMessageRecoverer：重试耗尽后，返回nack，消息重新入队
    RepublishMessageRecoverer：重试耗尽后，将失败消息投递到指定的交换机
 */
@Configuration
public class ErrorMessageConfig {

    //异常队列
    @Bean
    public Queue queue() {
        return new Queue("error:queue");
    }

    //异常交换机
    @Bean
    public DirectExchange exchange() {
        return new DirectExchange("error:exchange");
    }

    @Bean
    public Binding binding(Queue queue, DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("error:red");
    }
    //消息重发  发送到异常交换机
    @Bean
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate) {
        return new RepublishMessageRecoverer(rabbitTemplate,
                "error:exchange", "error:red");
    }
}
